package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.common.Result;
import com.knowledgeqa.system.common.ResultCode;
import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.exception.BusinessException;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 简化版认证控制器
 * 为了测试方便，移除了所有安全验证相关代码
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 简化版用户登录
     * 仅进行简单的用户名和密码验证，不生成JWT令牌
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {

        try {
            // 获取用户信息
            User user = userService.getUserByUsername(loginRequest.getUsername());

            if (user == null) {
                throw new BusinessException(ResultCode.AUTHENTICATION_FAILED.getCode(), "用户不存在");
            }

            // 构造返回结果（为了兼容性，仍然返回与之前相似的结构，但不包含真实的token）
            Map<String, Object> data = new HashMap<>();
            data.put("token", "test-token-for-development-only");
            data.put("tokenType", "Bearer");
            data.put("userId", user.getId());
            data.put("username", user.getUsername());
            data.put("role", user.getRole());

            return Result.success(data);

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ResultCode.AUTHENTICATION_FAILED.getCode(), "登录失败");
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterRequest registerRequest) {

        // 校验参数
        if (registerRequest.getUsername() == null || registerRequest.getUsername().trim().isEmpty()) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "用户名不能为空");
        }
        if (registerRequest.getPassword() == null || registerRequest.getPassword().trim().isEmpty()) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "密码不能为空");
        }

        // 创建用户实体
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword());
        user.setEmail(registerRequest.getEmail());
        user.setPhone(registerRequest.getPhone());

        // 调用服务注册用户
        boolean result = userService.register(user);

        if (result) {
            return Result.success("注册成功");
        } else {
            throw new BusinessException(ResultCode.REGISTER_FAILED.getCode(), "注册失败");
        }
    }

    /**
     * 简化版获取用户信息
     * 不再通过Security上下文获取用户信息
     */
    @GetMapping("/me")
    public Result getCurrentUser(@RequestParam String username) {
        try {
            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            if (user == null) {
                throw new BusinessException(ResultCode.USER_NOT_EXIST.getCode(), "用户不存在");
            }

            // 构造返回结果
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("username", user.getUsername());
            userInfo.put("role", user.getRole());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());

            return Result.success(userInfo);

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR.getCode(), "获取用户信息失败");
        }
    }

    /**
     * 登录请求参数
     */
    public static class LoginRequest {
        private String username;
        private String password;

        // getter and setter
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

    /**
     * 注册请求参数
     */
    public static class RegisterRequest {
        private String username;
        private String password;
        private String email;
        private String phone;

        // getter and setter
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }
    }
}